package atomic.atomicUpdater;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author ZhuQi
 * @ClassName AtomicIntegerFieldUpdater
 * @Date 2022/9/16 13:34
 * @Version 1.0
 * @Description AtomicIntegerFieldUpdater 测试
 */
@Slf4j
public class AtomicIntegerFieldUpdaterDemo {

    /**
     * 测多线程修改 对象 的int 值
     * @param args
     */
    @SneakyThrows
    public static void main(String[] args) {
        Resources resources = new Resources();
        AtomicIntegerFieldUpdater<Resources> atomicIntegerFieldUpdater =
                AtomicIntegerFieldUpdater.newUpdater(Resources.class, "count");
        CountDownLatch countDownLatch = new CountDownLatch(2);

        new Thread(()->{
            boolean b = atomicIntegerFieldUpdater.compareAndSet(resources, 0, 1);
            String threadName = Thread.currentThread().getName();
            int i = atomicIntegerFieldUpdater.get(resources);
            log.info("{} 结果:{} 值:{}", threadName, b, i);
            countDownLatch.countDown();
        }, "thread1").start();

        new Thread(()->{
            boolean b = atomicIntegerFieldUpdater.compareAndSet(resources, 0, 1);
            String threadName = Thread.currentThread().getName();
            int i = atomicIntegerFieldUpdater.get(resources);
            log.info("{} 结果:{} 值:{}", threadName, b, i);
            countDownLatch.countDown();
        }, "thread2").start();

        countDownLatch.await();
        log.info("resource:{}",resources);
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Resources {

    private String name;

    public volatile int count;
}